﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using Hx.Infrastructure.Authorization;
using Hx.Infrastructure.Helpers;

namespace Hx.Client
{
    public partial class LoginWindow
    {
        private const string ClientId = "WPFClient";
        private const string ClientSecret = "~!@#WPFClient@#!";

        public LoginWindow()
        {
            InitializeComponent();
            WebApiHelper.SetBaseAddress(UrlDefinition.BaseAddress);
            WebApiHelper.SetAuthentication(
                "Basic",
                Convert.ToBase64String(Encoding.ASCII.GetBytes(ClientId + ":" + ClientSecret)));
        }

        private void Sure_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Loading.Visibility = Visibility.Visible;
                var result = WebApiHelper.PostResponse<AccessTokenResult>(UrlDefinition.Token,
                    new Dictionary<string, string>
                    {
                        {"grant_type", "password"},
                        {"username", UserName.Text},
                        {"password", Password.Password}
                    });
                var mainWindow = new MainWindow(result);
                mainWindow.Show();
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("用户名和密码不匹配", "登录消息", MessageBoxButton.OK);
                Loading.Visibility = Visibility.Collapsed;
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}